package com.example.homework8.fragment;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.Group;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.example.homework8.R;
import com.example.homework8.bean.RecordInfo;
import com.example.homework8.bean.TagBean;
import com.example.homework8.database.MySQLHelper;
import com.example.homework8.database.PlanDBHelper;
import com.example.homework8.database.RecordDBHelper;
import com.example.homework8.utils.BitmapUtil;
import com.example.homework8.utils.RepeatingAlarm;
import com.example.homework8.utils.SharedUtil;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static android.content.ContentValues.TAG;
import static android.content.Context.ALARM_SERVICE;


public class RecordEditFragment extends Fragment  implements View.OnClickListener, TakePhoto.TakeResultListener, InvokeListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    RecordInfo recordInfo;

    public RecordEditFragment(RecordInfo recordInfo ) {
        // Required empty public constructor
        this.recordInfo = recordInfo;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AddRecordFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RecordEditFragment newInstance(String param1, String param2) {
        RecordEditFragment fragment = new RecordEditFragment(new RecordInfo());
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    Button sure;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    private Toolbar mToolbar;
    private EditText etTitle;
    private EditText etContent;
    private TextView tvRemindTime,tvTag;
    private Switch aSwitch;
    private ImageView iv,ivEdit,ivClock;

    private MySQLHelper mySQLiteOpenHelpter = null;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private String image = null;
    //时间选择器
    private TimePickerView pvTime;
    //条件选择器
    private OptionsPickerView pvOptions;

    private List<TagBean> tagBeanList = new ArrayList<>();
    String imgurl ;
    private int tag = -1;
    Button savebtn;
    private Date alermdate;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_add_record, container, false);

        etTitle = view.findViewById(R.id.etTitle);
        etContent = view.findViewById(R.id.etContent);
        tvRemindTime = view.findViewById(R.id.tvRemindTime);
        tvRemindTime.setOnClickListener(this);
        tvTag = view.findViewById(R.id.tvTag);
        tvTag.setOnClickListener(this);
        aSwitch = view.findViewById(R.id.mSwitch);
        iv = view.findViewById(R.id.iv);
        iv.setOnClickListener(this);
        ivEdit = view.findViewById(R.id.ivEdit);
        ivEdit.setOnClickListener(this);
        ivClock = view.findViewById(R.id.ivClock);
        ivClock.setOnClickListener(this);

        tvRemindTime.setText(recordInfo.alermtime);
        etTitle.setText(recordInfo.name);
        etContent.setText(recordInfo.info);
        tvTag.setText(recordInfo.cate);
        iv.setImageBitmap(BitmapFactory.decodeFile(recordInfo.imgurl));
        this.imgurl = recordInfo.imgurl;
        //时间选择器
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                alermdate = date;
                tvRemindTime.setText(new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(date));
            }
        }).setType(new boolean[]{true, true, true, true, true, false}).build();
        savebtn = view.findViewById(R.id.savebtn);
        savebtn.setOnClickListener(this::onClick);
        pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                tag = tagBeanList.get(options1).getId();
                tvTag.setText(tagBeanList.get(options1).getText());
            }
        }).build();

        queryTag();
        return  view;
    }

    private void queryTag(){
        //3.执行select 对应的sql语句 的方法  sql:sql语句    selectionArgs：占位符的参数值
        //初始化数据
        if (mySQLiteOpenHelpter == null){
            mySQLiteOpenHelpter = new MySQLHelper(getActivity());
        }

        SQLiteDatabase mDataBase
                = mySQLiteOpenHelpter.getWritableDatabase();
        Cursor cursor = mDataBase.rawQuery("select * from tag", null);
        //4.解析结果集
        //判断结果集是否有效
        if (cursor != null && cursor.getCount() > 0) {
            List<TagBean> list = new ArrayList<>();
            while (cursor.moveToNext()) {//游标是否继续向下移动
                TagBean bean = new TagBean();
                //通过列的索引获取对应的数据
                bean.setId(cursor.getInt(cursor.getColumnIndex("tag_id")));
                bean.setText(cursor.getString(cursor.getColumnIndex("describe")));
                list.add(bean);
            }
            //关闭cursor
            cursor.close();
            tagBeanList.clear();
            tagBeanList.addAll(list);
            pvOptions.setPicker(tagBeanList);
        }else {
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvRemindTime:
                pvTime.show();
                break;
            case R.id.tvTag:
                pvOptions.show();
                break;
            case R.id.iv:
                Intent intent2 = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 以startActivityForResult的方式启动一个activity用来获取返回的结果
                startActivityForResult(intent2, 1);
                break;
            case R.id.ivEdit:
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.id_content, new TagFragment(), null)
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.ivClock:
                Calendar c = Calendar.getInstance();
                Intent intent = new Intent(getActivity(), RepeatingAlarm.class);
                intent.setAction("com.gcc.alarm");
                PendingIntent op = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
                // 启动一次只会执行一次的闹钟
                AlarmManager am = (AlarmManager)getActivity().getSystemService(ALARM_SERVICE);
                am.set(AlarmManager.RTC, alermdate.getTime(), op);
                Toast.makeText(getActivity(),"闹钟已设置为" + tvRemindTime.getText().toString(),Toast.LENGTH_SHORT).show();
                break;
            case R.id.savebtn:
                RecordInfo newRecord = new RecordInfo();
                newRecord.imgurl = imgurl;
                newRecord.rowid = recordInfo.rowid;
                newRecord.name = etTitle.getText().toString();
                newRecord.alermtime = tvRemindTime.getText().toString();
                newRecord.cate = tvTag.getText().toString();
                newRecord.info = etContent.getText().toString();
                newRecord.username = SharedUtil.getIntance(getActivity()).readShared("loginuser","null");

                RecordDBHelper.getInstance(getActivity(),1).update(newRecord);
                Log.d(TAG, "onClick: " + newRecord.toString());
                Toast.makeText(getActivity(),"添加完成",Toast.LENGTH_SHORT).show();
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.id_content, new MainFragment(), null)
                        .addToBackStack(null)
                        .commit();
                break;
        }
    }

    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this::invoke).bind(new TakePhotoImpl(this,this));
            CompressConfig config=new CompressConfig.Builder()
                    .setMaxSize(50*1024)
                    .setMaxPixel(800)
                    .create();
            takePhoto.onEnableCompress(config,true);
        }
        return takePhoto;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode ==1){

            Uri uri = data.getData();
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            iv.setImageBitmap(bitmap);
            String name = UUID.randomUUID().toString().substring(24)+".png";
            imgurl =  BitmapUtil.saveImgToDisk(name,bitmap);
        }
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }

    @Override
    public void takeSuccess(TResult result) {
        image = result.getImage().getOriginalPath();
        Glide.with(getActivity()).load(image).into(iv);
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }
}